package com.czh.subject.domain.handler.subject;

import com.czh.subject.common.enums.SubjectTypeEnum;
import com.czh.subject.domain.convert.SubjectRadioConverter;
import com.czh.subject.domain.entity.SubjectAnswerAndOptionBO;
import com.czh.subject.domain.entity.SubjectInfoBO;
import com.czh.subject.domain.entity.SubjectOptionBO;
import com.czh.subject.infra.basic.entity.SubjectRadio;
import com.czh.subject.infra.basic.service.SubjectRadioService;
import com.google.common.base.Preconditions;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author czh01
 * @version 1.0
 * @description: 单选题策略
 * @date 2024/7/31 下午 2:29
 */
@Component
@Log4j2
public class RadioTypeHandler implements SubjectTypeHandler {
    @Resource
    private SubjectRadioService subjectRadioService;

    @Override
    public SubjectTypeEnum getHandlerType() {
        return SubjectTypeEnum.RADIO;
    }

    @Override
    public boolean add(SubjectInfoBO subjectInfoBO) {
        try {
            Preconditions.checkNotNull(subjectInfoBO.getOptionList(), "题目答案和选项不能为空!");
            List<SubjectRadio> subjectRadioList = subjectInfoBO.getOptionList().stream().map(option -> {
                SubjectRadio subjectRadio = SubjectRadioConverter.INSTANCE.convert(option);
                subjectRadio.setSubjectId(subjectInfoBO.getId());
                return subjectRadio;
            }).toList();
            return subjectRadioService.saveBatch(subjectRadioList);
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public SubjectAnswerAndOptionBO queryOptionAndAnswer(Long id) {
        SubjectRadio subjectRadio = new SubjectRadio();
        subjectRadio.setSubjectId(id);
        List<SubjectRadio> subjectRadioList = subjectRadioService.querySubjectRadioList(subjectRadio);
        SubjectAnswerAndOptionBO subjectAnswerAndOptionBO = new SubjectAnswerAndOptionBO();
        List<SubjectOptionBO> subjectOptionBOList = SubjectRadioConverter.INSTANCE.convert(subjectRadioList);
        subjectAnswerAndOptionBO.setOptionList(subjectOptionBOList);
        return subjectAnswerAndOptionBO;
    }
}
